package com.czk.client;

import com.czk.codec.ObjDecoder;
import com.czk.codec.ObjEncoder;
import com.czk.msg.Request;
import com.czk.msg.Response;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/4/27 11:31
 */
public class ClientSocket implements Runnable {
    private ChannelFuture channelFuture;

    @Override
    public void run() {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.AUTO_READ, true);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(
                            new ObjDecoder(Response.class),
                            new ObjEncoder(Request.class),
                            new MyClientHandler()
                    );
                }
            });
            ChannelFuture f = b.connect("127.0.0.1", 7397).sync();
            this.channelFuture = f;
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }

    public ChannelFuture getFuture() {
        return channelFuture;
    }

    public void setFuture(ChannelFuture future) {
        this.channelFuture = future;
    }
}
